import router from "./router";
import { useUserStore } from "./stores/useUserStore";

router.beforeEach((to, from, next) => {
  const useStore = useUserStore()
  const { userRef } = useStore

  if (to.path === '/' && userRef.type) {
    if (from.query.redirect) {
      next({ path: from.query.redirect })
    } else {
      next({ name: 'Dashboard' })
    }

  } else if (to.path === '/' && !userRef.type) {
    if (from.query.redirect) {
      next({ path: from.query.redirect })

    } else {
      next({ name: 'Home' })
    }

  }

  if (JSON.stringify(userRef) === "{}" && to.name !== 'Login') {
    if (to.path === "/home" || to.path === '/ashboard') {
      next({ name: 'Login' })
    } else {
      next({ name: 'Login', query: { redirect: to.path } })
    }
  }

  next()
})